package server

import (
    "github.com/wubo19842008/gowxtks/server/config"
    "github.com/wubo19842008/gowxtks/server/controller"
    "log"
    "net/http"
    "strconv"
)

type TkServer struct {
    Port     int
    Host     string
    WxConfig map[string]config.WxConfig
}

func Create(configFilePath string) TkServer {
    c, _ := config.LoadConfig(configFilePath)
    server := TkServer{}
    server.Host = c.Host
    server.Port = c.Port
    server.WxConfig = c.Config
    return server
}

func (server *TkServer) Start() error {
    var err error
    mut := http.NewServeMux()
    tokenCtrl := controller.TokenCtrl{server.WxConfig}
    ticketCtrl := controller.TicketCtrl{server.WxConfig}

    //init url route
    mut.HandleFunc("/token/get", tokenCtrl.Get)
    mut.HandleFunc("/token/refresh", tokenCtrl.Refresh)

    mut.HandleFunc("/ticket/get", ticketCtrl.Get)
    mut.HandleFunc("/ticket/refresh", ticketCtrl.Refresh)

    err = http.ListenAndServe(server.Host+":"+strconv.Itoa(server.Port), mut)
    if err != nil {
        log.Println(err)
        log.Println("occurred error when start tkserver")
    }
    return err
}
